package cn.tuling.json;

import cn.tuling.entity.Student;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.boot.jackson.JsonObjectSerializer;

import java.io.IOException;

/**
 * 使用场景：
 * 1. 一次查询不完完整的返回数据，需要多次数据库查询
 * 2. 根据不同角色返回不同数据
 */
@JsonComponent
public class StudentJsonCustom {
    public static class Serializer extends JsonObjectSerializer<Student> {
        @Override
        protected void serializeObject(Student value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeObjectField("id", "1");
            jgen.writeObjectField("name", "就这个名字");
            jgen.writeFieldName("level");
            jgen.writeObject("A");
        }
    }

    public static class Deserializer extends JsonObjectDeserializer<Student> {
        @Override
        protected Student deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, JsonNode tree) throws IOException {
            Student student = new Student();
            student.setId(tree.findValue("id").asInt());
            student.setName(tree.findValue("name").asText());
            student.setLevel(tree.findValue("l").asText());
            return student;
        }
    }
}
